package com.axing.yuhaigui.manager;

import com.volcengine.ark.runtime.model.completion.chat.ChatCompletionRequest;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessage;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessageRole;
import com.volcengine.ark.runtime.service.ArkService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * Author: 阿星程序员
 * Date: 2025/3/23
 * Function Description:
 *  代码复用
 *  Ai调用工具类
 */
@Service
public class AiManager {
    @Resource
    private ArkService arkService;

        /**
         * 聊天 只允许传入用户预设 和 系统预设
         *
         */
    public String doChat(String systemPrompt, String userPrompt) {
        final List<ChatMessage> streamMessages = new ArrayList<>();
        final ChatMessage streamSystemMessage = ChatMessage.builder().role(ChatMessageRole.SYSTEM).content(systemPrompt).build();
        final ChatMessage streamUserMessage = ChatMessage.builder().role(ChatMessageRole.USER).content(userPrompt).build();
        streamMessages.add(streamUserMessage);
        streamMessages.add(streamSystemMessage);

        /*单次调用*/
     return   doChat(streamMessages);
    }


    /**
     *代码复用
     *该方法实现了 上下文
     * 允许用户传入任意消息列表
     */

    public String doChat(List<ChatMessage> chatMessages) {

        /*单次调用*/
        ChatCompletionRequest streamChatCompletionRequest = ChatCompletionRequest.builder()
                .model("ep-20250323155401-b4zw8")
                .messages(chatMessages)
                .build();

        StringBuilder strBuilder = new StringBuilder();

        arkService.streamChatCompletion(streamChatCompletionRequest)
                .doOnError(Throwable::printStackTrace)
                .blockingForEach(
                        delta -> {
                            if (!delta.getChoices().isEmpty()) {
                                if (StringUtils.isNotEmpty(delta.getChoices().get(0).getMessage().getReasoningContent())) {
                                    /*System.out.print(delta.getChoices().get(0).getMessage().getReasoningContent());*/
                                    strBuilder.append(delta.getChoices().get(0).getMessage().getReasoningContent());
                                } else {
                                    /*System.out.print(delta.getChoices().get(0).getMessage().getContent());*/
                                    strBuilder.append(delta.getChoices().get(0).getMessage().getContent());
                                }
                            }
                        }
                );

        System.out.printf("Ai Chat completed: %s\n", strBuilder.toString());
        return strBuilder.toString();
    }


}